How to calculate the difference between Two Dates in C#?
How to calculate the difference between Two Dates in C#?
I completed my post-graduation in 2013 in the engineering field. Engineering is the application of science and math to solve problems. Engineers figure out how things work and find practical uses for scientific discoveries. Scientists and inventors often get the credit for innovations that advance the human condition, but it is engineers who are instrumental in making those innovations available to the world. I love pet animals such as dogs, cats, etc.
Ravi Vishwakarma
10-Jun-2024You can calculate the difference between two dates using the
DateTimestructure and its associated methods. TheDateTimestructure has aSubtractthe method that returns aTimeSpanobject representing the difference between twoDateTimeinstances. TheTimeSpanobject provides properties to get the difference in days, hours, minutes, seconds, and more.Here’s how you can calculate the difference between two dates:
Example -
Explanation
Create
DateTimeInstances: CreateDateTimeinstances for the start date and end date. You can use theDateTimeconstructor to create specific dates or use properties likeDateTime.Nowfor the current date and time.Calculate the Difference: Subtract the start date from the end date using the
-operator or theSubtractmethod. This returns aTimeSpanobject.Access
TimeSpanProperties: Use properties of theTimeSpanobject to get the difference in various units:Days: Gets the total number of whole days.TotalHours: Gets the total number of hours, including fractional hours.TotalMinutes: Gets the total number of minutes, including fractional minutes.TotalSeconds: Gets the total number of seconds, including fractional seconds.Read more: DateTime shorting in C#